// 工具函数封装

// 日期格式化
function formatDate(date, format = 'YYYY-MM-DD') {
    if (!date) return '';
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    
    return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
}

// 生成唯一ID
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 深拷贝
function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 显示提示消息
function showMessage(message, type = 'info', duration = 3000) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} fixed top-4 right-4 z-50 shadow-lg`;
    toast.innerHTML = `
        <div>
            <span>${message}</span>
        </div>
    `;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, duration);
}

// 显示确认对话框
function showConfirm(message, onConfirm, onCancel) {
    const modal = document.createElement('div');
    modal.className = 'modal modal-open';
    modal.innerHTML = `
        <div class="modal-box">
            <h3 class="font-bold text-lg">确认操作</h3>
            <p class="py-4">${message}</p>
            <div class="modal-action">
                <button class="btn btn-primary" id="confirm-btn">确认</button>
                <button class="btn" id="cancel-btn">取消</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    document.getElementById('confirm-btn').onclick = () => {
        modal.remove();
        if (onConfirm) onConfirm();
    };
    
    document.getElementById('cancel-btn').onclick = () => {
        modal.remove();
        if (onCancel) onCancel();
    };
}

// 显示模态框
function showModal(title, content, onClose) {
    const modal = document.createElement('div');
    modal.className = 'modal modal-open';
    modal.innerHTML = `
        <div class="modal-box max-w-4xl">
            <h3 class="font-bold text-lg">${title}</h3>
            <div class="py-4">
                ${content}
            </div>
            <div class="modal-action">
                <button class="btn" onclick="this.closest('.modal').remove()">关闭</button>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    if (onClose) {
        modal.querySelector('.btn').onclick = () => {
            modal.remove();
            onClose();
        };
    }
}

// 导出数据到CSV
function exportToCSV(data, filename) {
    if (!data || data.length === 0) {
        showMessage('没有数据可导出', 'warning');
        return;
    }
    
    const headers = Object.keys(data[0]);
    const csvContent = [
        headers.join(','),
        ...data.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
    ].join('\n');
    
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();
}

// 导出数据到Excel
function exportToExcel(data, filename) {
    if (!data || data.length === 0) {
        showMessage('没有数据可导出', 'warning');
        return;
    }
    
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    XLSX.writeFile(workbook, filename);
}

// 检查日期是否延期
function isOverdue(date, days = 0) {
    if (!date) return false;
    const targetDate = new Date(date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    targetDate.setHours(0, 0, 0, 0);
    
    if (days > 0) {
        targetDate.setDate(targetDate.getDate() + days);
    }
    
    return targetDate < today;
}

// 计算剩余天数
function getRemainingDays(date) {
    if (!date) return null;
    const targetDate = new Date(date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    targetDate.setHours(0, 0, 0, 0);
    
    const diffTime = targetDate - today;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    
    return diffDays;
}

// 获取状态颜色
function getStatusColor(status) {
    const statusColors = {
        'pending': 'warning',
        'in-progress': 'info',
        'completed': 'success',
        'overdue': 'error',
        'cancelled': 'ghost'
    };
    return statusColors[status] || 'ghost';
}

// 获取状态文本
function getStatusText(status) {
    const statusTexts = {
        'pending': '待处理',
        'in-progress': '进行中',
        'completed': '已完成',
        'overdue': '已延期',
        'cancelled': '已取消'
    };
    return statusTexts[status] || status;
}

// 验证表单数据
function validateForm(formData, rules) {
    const errors = {};
    
    for (const [field, rule] of Object.entries(rules)) {
        const value = formData[field];
        
        if (rule.required && !value) {
            errors[field] = `${rule.label || field}不能为空`;
            continue;
        }
        
        if (rule.pattern && value && !rule.pattern.test(value)) {
            errors[field] = rule.message || `${rule.label || field}格式不正确`;
        }
        
        if (rule.minLength && value && value.length < rule.minLength) {
            errors[field] = `${rule.label || field}最少需要${rule.minLength}个字符`;
        }
        
        if (rule.maxLength && value && value.length > rule.maxLength) {
            errors[field] = `${rule.label || field}最多允许${rule.maxLength}个字符`;
        }
    }
    
    return Object.keys(errors).length > 0 ? errors : null;
}

// 显示加载状态
function showLoading(element, message = '加载中...') {
    element.innerHTML = `
        <div class="flex items-center justify-center p-8">
            <div class="loading mr-2"></div>
            <span>${message}</span>
        </div>
    `;
}

// 隐藏加载状态
function hideLoading(element) {
    element.innerHTML = '';
}

// 获取文件扩展名
function getFileExtension(filename) {
    return filename.split('.').pop().toLowerCase();
}

// 读取JSON文件
function readJSONFile(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = JSON.parse(e.target.result);
                resolve(data);
            } catch (error) {
                reject(new Error('JSON文件格式错误'));
            }
        };
        reader.onerror = () => reject(new Error('文件读取失败'));
        reader.readAsText(file);
    });
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
